const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ParallelUglifyPlugin  = require('webpack-parallel-uglify-plugin');
// css
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const HappyPack = require('happypack');

const { merge } = require('webpack-merge');
const baseCfg = require('./webpack.base');




const proCfg = {
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash:8].js',
    publicPath: 'https://cdn/yuyang'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: ['happypack/loader'],
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use:[{
          loader: 'url-loader',
          options: {
            // 小于 5kb 图片用 base64 格式
            // 否则 依然使用 file-loader 产出 到 assert目录
            limit: 5*1024,
            outputPath: '/assets/',
          }
        }]
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader', 'postcss-loader']
      }
    ]
  },

  plugins:[
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: 'css/[name][contenthash:8].css'
    }),
    new HappyPack({
      loaders:['babel-loader?cacheDirectory']
    }),
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/
    }),
    new ParallelUglifyPlugin({
      uglifyJS: {
        output: {},
        compress: {

        }
      }
    })
  ],
  optimization: {
    // 压缩Css
    minimizer: [new TerserPlugin(), new OptimizeCssAssetsPlugin()],

    // 分割代码
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        // 第三方模块
        vendor: {
          name: 'vendor',
          priority: 1, //权限更高 优先抽离
          test: /[\\/]node_modules[\\/]/,
          minSize: 0,
          minChunks: 1 //代码中 重复引用次数 第三方引用一次 就分离
        },
        // 公用模块
        default: {
          name: 'common',
          priority: 0,
          minSize: 0, // 太小的包不做分离 此处0 为了调试效果
          minChunks: 2, //代码中 重复引用次数
        }

      }
    }
  }
}

module.exports = merge(baseCfg, proCfg);